﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace 自动分享工具
{
    public partial class Form1
    {
        #region 公有方法
        /// <summary>
        /// post登录到搜狐
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="loginurl"></param>
        /// <returns></returns>
        public bool loginSohu(string username, string password, string loginurl)
        {
            CookieContainer cc = new CookieContainer();
            string postData = string.Format("?userid={0}&password={1}&appid=9998&persistentcookie=0&isSLogin=1&s=1308584053421&b=2&w=1600&pwdtype=1&v=26", username, password);
            //byte[] bytePost = Encoding.UTF8.GetBytes(postData);
            byte[] bytePost = Encoding.UTF8.GetBytes("");

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(loginurl + postData));
                myRequest.CookieContainer = cc;
                myRequest.Method = "POST";
                myRequest.ContentType = "applicatin/x-www-form-urlencoded";
                myRequest.ContentLength = bytePost.Length;
                Stream newStream = myRequest.GetRequestStream();
                //send the data
                newStream.Write(bytePost, 0, bytePost.Length);
                newStream.Close();

                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                string responsetxt = sr.ReadToEnd();

                //richTextBox1.AppendText(responsetxt);

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            return true;
        }

        public bool postSohu(string postUrl, string postData)
        {
            //string msg = "";
            string picUrl = "";
            CookieContainer cc = new CookieContainer();
            postData = string.Format("act=insertTwitter&msg={0}&type=60&pic={1}", postData, picUrl);
            byte[] bytePost = Encoding.UTF8.GetBytes(postData);

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                myRequest.CookieContainer = cc;
                myRequest.Method = "POST";
                myRequest.ContentType = "applicatin/x-www-form-urlencoded";
                myRequest.ContentLength = bytePost.Length;
                Stream newStream = myRequest.GetRequestStream();
                //send the data
                newStream.Write(bytePost, 0, bytePost.Length);
                newStream.Close();

                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                string responsetxt = sr.ReadToEnd();

                //richTextBox1.AppendText(responsetxt);

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            return true;
        }

        /// <summary>
        /// 登录百度帐号
        /// </summary>
        private bool loginBaidu(string username, string password)
        {
            //richTextBox2.AppendText(DateTime.Now + " 登录百度\n");
            HtmlElement he = webBrowser1.Document.All["username_normal"];
            if (he != null)
            {
                he.SetAttribute("value", username);
            }
            he = webBrowser1.Document.All["normModPsp"];
            if (he != null)
            {
                he.SetAttribute("value", password);
            }

            string str = null;
            for (int i = 0; i < webBrowser1.Document.All.Count; i++)
            {
                str = webBrowser1.Document.All[i].GetAttribute("value");
                if (str != null && str.Trim() == "登录")
                {
                    he = webBrowser1.Document.All[i];
                    he.InvokeMember("click");

                    //while (webBrowser1.Document.Title.Trim()!="个人资料")
                    //{
                    //    Application.DoEvents();
                    //    he.InvokeMember("click");
                    //}
                    //richTextBox2.AppendText(DateTime.Now + "\n" + username + " 登录百度\n");

                    Application.DoEvents();
                    System.Threading.Thread.Sleep(3000);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 发帖子到百度贴吧
        /// </summary>
        /// <param name="context">帖子评论内容</param>
        /// <returns></returns>
        public bool postBaiduTieba(string context)
        {
            //HtmlElement he = webBrowser1.Document.All["comment"];
            HtmlElement he = webBrowser1.Document.GetElementById("comment");
            if (null != he)
            {
                he.SetAttribute("value", context);
            }
            string str = null;
            for (int i = 0; i < webBrowser1.Document.All.Count; i++)
            {
                str = webBrowser1.Document.All[i].GetAttribute("name");
                if (str != null && str.Trim() == "share")
                {
                    he = webBrowser1.Document.All[i];
                    he.InvokeMember("click");
                    while (webBrowser1.IsBusy)
                    {
                        Application.DoEvents();
                    }
                    richTextBox2.AppendText(DateTime.Now + " 发帖到百度贴吧\n");

                    isPosted = true;
                    Application.DoEvents();
                    return true;
                }
            }

            return false;
        }

        private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;

        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

        /// <summary>
        /// 设置cookie
        /// </summary>
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

        /// <summary>
        /// 获取cookie
        /// </summary>
        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetGetCookie(string url, string name, StringBuilder data, ref int dataSize);

        //Call this method to clear session
        public void cleanBrowserSessionByWininet()
        {
            //string url = baiduLoginUrl;
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);
            //InternetSetCookie(url, null, ";expires=Thu, 01-Jan-1970 00:00:01 GMT");
            //webBrowser1.Navigate(url);
        }

        public void cleanBrowserSenssionByJs()
        {
            webBrowser1.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())");
            //string url = baiduLoginUrl;
            //webBrowser1.Navigate(url);
        }

        public bool removeIETempFile(string metaString)
        {

            try
            {
                IETempFile ieTempFile = new IETempFile();
                List<string> tempFiles = ieTempFile.SearchTempFile(metaString);
                ieTempFile.RemoveTempFile(tempFiles);
                return true;
            }
            catch
            {
                return false;
            }
        }


        public enum ShowCommands : int
        {
            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_FORCEMINIMIZE = 11,
            SW_MAX = 11
        }

        [DllImport("shell32.dll")]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd);

        //清除IE临时文件
        public void removeIECookies()
        {
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0);    //删除内存中的session
            ShellExecute(IntPtr.Zero, "open", "rundll32.exe", " InetCpl.cpl,ClearMyTracksByProcess 2", "", ShowCommands.SW_HIDE);   //删除硬盘上的cookies
            Application.DoEvents();
            System.Threading.Thread.Sleep(2000);
        }
        // Temporary Internet Files  （Internet临时文件）
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
        //Cookies
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
        //History (历史记录)
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
        //Form. Data （表单数据）
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
        //Passwords (密码）
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
        //Delete All  （全部删除）
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
        //Delete All - "Also delete files and settings stored by add-ons"
        //    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351


        #endregion
    }
}
